package com.tengju.bff.interfaces.covercharge.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.idanchuang.component.base.JsonResult;
import com.tengju.bff.interfaces.covercharge.constant.BankStatus;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeEnum;
import com.tengju.bff.interfaces.covercharge.constant.SignIdentityEnum;
import com.tengju.bff.interfaces.covercharge.constant.WithdrawalCancelEnum;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceAccount;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceBank;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceSign;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceSignLog;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceBankMapper;
import com.tengju.bff.interfaces.covercharge.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tengju.bff.interfaces.covercharge.service.message.client.UserMessageClient;
import com.idanchuang.service.base.sms.api.service.ISmsServiceProvider;
import com.tengju.user.application.sms.SmsBizService;
import com.tengju.user.domain.model.user.UserIdCode;
import com.tengju.user.domain.model.user.UserInfo;
import com.tengju.user.domain.model.user.UserInfoRepository;
import com.tengju.user.domain.service.UserDocService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.LocalDateTime;

/**
 * <p>
 * 银行账户表 服务实现类
 * </p>
 *
 * @author zhaoyi
 * @since 2020-02-24
 */
@Service
@Slf4j
public class ServiceBankServiceImpl extends ServiceImpl<ServiceBankMapper, ServiceBank> implements IServiceBankService {

    @Autowired
    private ISmsServiceProvider smsServiceProvider;

    @Autowired
    private IServiceAccountService accountService;

    @Autowired
    @Lazy
    private IServiceSignService signService;

    @Autowired
    private IServiceSignLogService signLogService;

    @Autowired
    @Lazy
    private LeTaxOneService leTaxOneService;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserDocService userDocService;

    @Autowired
    private SmsBizService smsBizService;

    @Autowired
    private ServiceBankMapper serviceBankMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbind(CoverChargeEnum.ServiceAccountType accountType, Integer userId, Integer idCode, String checkCode) throws Exception {


        UserInfo userInfo = userDocService.searchUserByIdCodeOrMobile(new UserIdCode(idCode),null);
        Assert.isTrue(userInfo != null, "查询会员接口失败");
        JsonResult<?> verify = smsServiceProvider.verify(userInfo.getMobile(), checkCode);
        log.debug("短信校验返回结果:{}", JSON.toJSONString(verify));
        //验证手机验证码
        Assert.isTrue(verify.isSuccess(), "短信验证码验证失败");

        ServiceSign serviceSignParam = new ServiceSign();
        serviceSignParam.setIdCode(idCode);
        serviceSignParam.setPlatformCode(accountType.getPlatform());
        ServiceSign serviceSign = signService.getOne(new QueryWrapper<>(serviceSignParam));
        // 判断是否签约
        Assert.isTrue(serviceSign != null && CoverChargeEnum.CommonStatus.YES.getName().equals(serviceSign.getIsSigned()), "未签约");
        Assert.isTrue(SignIdentityEnum.person.toString().equals(serviceSign.getCurrentIdentity()), "当前身份不正确");

        ServiceAccount serviceAccount = accountService.getAccount(accountType.getCode(), idCode);

        //更新bank
        ServiceBank serviceBankUp = new ServiceBank();
        serviceBankUp.setStatus(BankStatus.unlink.toString());
        serviceBankUp.setUpdatedAt(LocalDateTime.now());

        ServiceBank serviceBankWhere = new ServiceBank();
        serviceBankWhere.setIdCode(idCode);
        serviceBankWhere.setAccountId(serviceAccount.getId());
        boolean update = this.update(serviceBankUp, new UpdateWrapper<>(serviceBankWhere));
        Assert.isTrue(update,"更新收款账户失败");

        ServiceSign serviceSignUp = new ServiceSign();
        serviceSignUp.setIsSigned(CoverChargeEnum.CommonStatus.NO.getName());
        serviceSignUp.setHistoryIdentity(null);
        serviceSignUp.setCurrentIdentity(SignIdentityEnum.no_identity.toString());

        ServiceSign signWhere = new ServiceSign();
        signWhere.setPlatformCode(accountType.getPlatform());
        signWhere.setIdCode(idCode);
        signService.update(serviceSignUp, new UpdateWrapper<>(signWhere));

        ServiceSignLog serviceSignLog=new ServiceSignLog();
        serviceSignLog.setBeforeIdentity(SignIdentityEnum.person.toString());
        serviceSignLog.setLastIdentity(SignIdentityEnum.no_identity.toString());
        serviceSignLog.setCreatedBy(idCode+"");
        serviceSignLog.setCreatedTime(LocalDateTime.now());
        serviceSignLog.setIdCode(idCode);
        serviceSignLog.setOperateType("");
        serviceSignLog.setPlatformCode(accountType.getPlatform());
        signLogService.save(serviceSignLog);

        leTaxOneService.withdrawalApplyCancelNoTran(idCode, accountType.getPlatform(), null, WithdrawalCancelEnum.unbind);

        String content = "您已成功解绑服务费收款账户，您提交的服务费申请已自动取消。";

//        if(CoverChargeEnum.ServiceAccountType.CUSTOMER_TYPE.getPlatform().equals(accountType.getPlatform()))
//        {
////            userMessageClient.sendDtServiceFeeMessage(idCode, "收款账户解绑通知"
////                    , content, true, true, false);
//        }

        smsBizService.sendUnbindAccount(userInfo.getMobile());
        //userMessageClient.sendMobileMessage(idCode, content);
    }

    /**
     * 更新状态
     */
    @Override
    public void updateStatusToUnlink(Integer idCode, String platformCode){
        serviceBankMapper.updateStatusToUnlink(idCode,platformCode);
    }
}
